<template>
  <div>
      <div class="search-box d-flex">
          <div class="search-item d-flex a-center">
              <label>科目名称</label>
              <el-input v-model="subjectName" class="m-l10" style="width: auto !important;" placeholder="请输入科目名称"></el-input>
          </div>
          <div class="search-buttons m-l20">
              <el-button
                      color="#fc702b"
                      style="color:#fff;"
                      @click.prevent="onQuery"
              >查询</el-button>
              <el-button
                      color="#f0f0f0"
                      style="color: #000000"
                      @click.prevent="onReset"
              >重置</el-button>
              <el-divider class="m-l20 m-r20" direction="vertical" />
              <el-button @click="addHandle" class="button_edit m-r10">
                  新增
              </el-button>
              <el-button class="button_edit" @click="onExport">
                  <svg-icon icon-class="project-detail-icon-derive" class="icon-export m-r5"></svg-icon>
                  一键导出
              </el-button>
          </div>
      </div>
      <el-table
              class="m-t20"
              :data="tableData"
              style="width: 100%; margin-bottom: 20px"
              row-key="subjectId"
              border
      >
          <el-table-column prop="subjectName" label="科目名称" min-width="100"/>
          <el-table-column prop="subjectType" label="科目类型" min-width="100">
              <template #default="scope">
                  <span>{{['','资金预算科目','预算科目'][scope.row.subjectType] || '-'}}</span>
                  <el-button size="small" class="m-l50 button_funtion" @click="onCopyAccount(scope.row)">复制科目</el-button>
              </template>
          </el-table-column>
      </el-table>
  </div>

    <public-dialog
            :title="'新增资金预算科目'"
            :width="'40%'"
            :confirmButtonTitle="'确认'"
            v-model:visible="visible"
            @onConfirm="onConfirm"
    >
        <div class="public-dialog-content d-flex flex-column">
          <el-form
             ref="formRef"
            :model="form"
            :rules="rules"
             :inline="true"
          >
              <el-form-item label="父级科目">
                  <el-cascader
                          class="m-l10"
                          ref="cascaderRef"
                          v-model="form.tempId"
                          @change="cascaderChange"
                          :options="tableData"
                          :props="props"
                          clearable />
              </el-form-item>
              <el-form-item label="科目名称" prop="subjectName">
                  <el-input v-model="form.subjectName" placeholder="请输入科目名称"></el-input>
              </el-form-item>
          </el-form>
        </div>
    </public-dialog>
</template>

<script setup>
import {exportApi, fundManagementApi} from "@/api/businessFinance";
import {onMounted, reactive, ref} from "vue";
import {
    ElTable,
    ElTableColumn,
    ElForm,
    ElFormItem,
    ElCascader,
    ElMessage,
    ElDivider
} from "element-plus";
import PublicDialog from "@/components/PublicDialog.vue";
import {exportExcelFile, resetForm} from "@/common/utils/GlobalUtils";

const subjectName = ref('');

const form = reactive({
    parentLevel:'0',
    subjectName:'',
    parentSubjectId:'',
    subjectType:'1',
    tempId:''
});
const rules = reactive({
    subjectName:[
        { required: true, message: '请输入科目名称', trigger: 'blur' },
    ]
});
const props = {
    value:'subjectId',
    label:'subjectName',
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
}

let subjectList = [];

const getParentTree = (id, tree) => {
    let arr = [] //要返回的数组
    for (let i = 0; i < tree.length; i++) {
        let item = tree[i]
        arr = []
        arr.push(item) //保存当前节点id
        if (id === item.subjectId) {
            //判断当前id是否是默认id
            return arr //是则退出循环、返回数据
        } else {
            //否则进入下面判断，判断当前节点是否有子节点数据
            if (item.children && item.children.length > 0) {
                //合并子节点返回的数据
                arr = arr.concat(getParentTree(id, item.children ? item.children : []))
                console.log(arr)
                if (arr.map(item2 => (item2 ? item2.subjectId : '')).includes(id)) {
                    //如果当前数据中已包含默认节点，则退出循环、返回数据
                    return arr
                }
            }
        }
    }
}

function textCopy(t) {
    // 如果当前浏览器版本不兼容navigator.clipboard
    if (!navigator.clipboard) {
        const ele = document.createElement("input");
        ele.value = t;
        document.body.appendChild(ele);
        ele.select();
        document.execCommand("copy");
        document.body.removeChild(ele);
        if (document.execCommand("copy")) {
            console.log("复制成功！");
            ElMessage.success('复制成功！');
        } else {
            console.log("复制失败！");
            ElMessage.error('复制失败！');
        }
    } else {
        navigator.clipboard.writeText(t).then(function () {
            console.log("复制成功！");
            ElMessage.success('复制成功！');
        }).catch(function () {
            console.log("复制失败！");
            ElMessage.error('复制失败！');
        })
    }
}


/**
 * 复制科目
 * @param row
 */
const onCopyAccount = (row) => {
    let subjectList = getParentTree(row.subjectId,tableData.value);
    if(subjectList.length){
       let subjectNames =  subjectList.map(item=>{return  item.subjectName}).join('-');
       textCopy(subjectNames);
    }
}

/**
 * 获取子预算科目树状
 *
 */
const tableData = ref([]);
const getBudgetSubjectListPage = (param) => {
    fundManagementApi.getBudgetSubjectListPage(param).then(res=>{
        tableData.value = res.data;
    });
}

/**
 * 查询
 *
 */
const onQuery = () => {
    getBudgetSubjectListPage({subjectName:subjectName.value.trim()});
}

/**
 * 重置
 *
 */
const onReset = () => {
    subjectName.value = '';
    getBudgetSubjectListPage({subjectName:''});
}

/**
 * 导出
 *
 */
const onExport = () => {
    exportApi.getBudgetSubjectListLeadingOut({subjectName:subjectName.value.trim()}).then(res=>{
      if(res){
          exportExcelFile(res,'资金预算科目表');
      }
    });
}

/**
 * 新增
 *
 */
const visible = ref(false);
const addHandle = () => {
    visible.value = true;
}

/**
 * 创建资金预算科目
 * @param param
 */
const createBudgetSubject = (param,callback) => {
  fundManagementApi.createBudgetSubject(param).then(res=>{
    if(res.code === '200'){
        if(callback)callback(res);
    }
  });
}

/**
 * 弹窗确认时触发
 *
 */
const formRef = ref(null);
const onConfirm = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            createBudgetSubject(form,()=>{
                ElMessage.success('新增成功!');
                getBudgetSubjectListPage({
                    subjectName:''
                });
                visible.value = false;
                resetForm(form);
                form.subjectType = '1';
            });
        } else {
            console.log('error submit!', fields)
        }
    });
}

/**
 * 根据key通过递归获取对应的当前科目节点
 * @param arr 资金预算科目数据
 * @param key
 * @param value 需要查找的值
 * @return {*[]}
 */
const findTreeNode = (arr,key,value) => {
    let tempArr = []
    function query(arr) {
        arr.forEach(item => {
            tempArr.push(item)
            if (item.children) {
                query(item.children)
            }
        })
    }
    query(arr)
    return tempArr.filter((val)=>{
        if(val[key] === value){
            return val;
        }
    });
}

/**
 * 级联选择器下来选择时触发
 *
 */
const cascaderRef = ref(null);
const cascaderChange = (e) => {
    if(e===null){
        return;
    }
   form.parentSubjectId = e[e.length-1];
   let row =  findTreeNode(tableData.value,'subjectId',e[e.length-1]);
   form.parentLevel = row[0].level;
}

onMounted(()=>{
    getBudgetSubjectListPage({
        subjectName:''
    });
});
</script>

<style lang="scss" scoped>
</style>
